package handler

import (
	"github.com/julienschmidt/httprouter"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

const (
	VIDEO_DIR       = "./videos"
	MAX_UPLOAD_SIZE = 1024 * 1025 * 50
)

func StreamHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	vid := p.ByName("vid-id")
	vl := VIDEO_DIR + vid

	video, err := os.Open(vl)
	if err != nil {

	}
	w.Header().Set("Content-Type", "video-mp4")
	http.ServeContent(w, r, "", time.Now(), video)
	defer video.Close()
}

func UploadHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE)
	err := r.ParseMultipartForm(MAX_UPLOAD_SIZE)
	if err != nil {
		//400
		return
	}

	file, _, err := r.FormFile("file") //form
	if err != nil {
		//
		return
	}

	data, err := ioutil.ReadAll(file)
	if err != nil {
		return
	}

	fileName := p.ByName("vid-id")
	err = ioutil.WriteFile(VIDEO_DIR+fileName, data, 0666)
	if err != nil {
		return
	}
}
